package com.jason.shader.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.view.View;

import com.jason.shader.R;

/**
 * desc: 在Shader类中有一对setter和getter方法：
 *          setLocalMatrix(Matrix localM)和getLocalMatrix(Matrix localM)
 *          我们可以利用它们来设置或获取Shader的变换矩阵
 * user:jason
 * date:16-9-7
 * time:下午3:44
 */
public class ShaderView2  extends View {

    private static final int RECT_SIZE = 400; //矩形尺寸的一半

    private Paint mPaint; // 画笔

    private int left, top, right, bottom; // 矩形做左上右下坐标
    private int screenX , screenY;


    public ShaderView2(Context context, AttributeSet attrs) {
        super(context, attrs);

        int width = getResources().getDisplayMetrics().widthPixels;
        int height = getResources().getDisplayMetrics().heightPixels;

        screenX = width / 2;
        screenY = height / 2;

        // 计算矩形左上右下坐标值
        left = screenX - RECT_SIZE;
        top = screenY - RECT_SIZE;
        right = screenX + RECT_SIZE;
        bottom = screenY + RECT_SIZE;

        // 实例化画笔
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        // 获取位图
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.a);

        // 实例化shader
        BitmapShader bitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);

        // 实例化矩阵
        Matrix matrix = new Matrix();
        // 设置矩阵变换
        matrix.setTranslate(left, top);
        // 设置shader的变换矩阵
        bitmapShader.setLocalMatrix(matrix);
        // 设置着色器
        mPaint.setShader(bitmapShader);

    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawRect(left, top, right, bottom, mPaint);
    }
}
